/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.coworkboard.controller;

import com.coworkboard.entities.Page;
import com.coworkboard.store.PageStore;
import com.google.appengine.api.blobstore.BlobInfo;
import com.google.appengine.api.blobstore.BlobInfoFactory;
import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.Query;
import com.google.gson.Gson;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.gmr.web.multipart.GMultipartFile;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

/**
 *
 * @author xavier
 */
@Controller
public class coworkboard {

    PageStore pageStore = new PageStore();
    BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();

    @RequestMapping("/run/{id}")
    public void runId(@PathVariable("id") Integer id, HttpServletResponse response) throws IOException {
        // SELECT Page key
        try {
        DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
        Query q = new Query("Page").setKeysOnly();

        List<Entity> results = datastore.prepare(q).asList(FetchOptions.Builder.withDefaults());
        Key key = results.get(results.size() - (id % results.size()) - 1).getKey();
        q = new Query("Page").addFilter(Entity.KEY_RESERVED_PROPERTY, Query.FilterOperator.EQUAL,key);
        Entity entity = datastore.prepare(q).asSingleEntity();
        Page page = new Page(entity);
        Gson gson = new Gson();
        String out = gson.toJson(page);
        System.out.println(out);
        
        response.setContentType("application/json; charset=utf-8");
        response.setCharacterEncoding("UTF-8");
        OutputStreamWriter osw = new OutputStreamWriter(response.getOutputStream(),"utf-8");
        osw.write(out, 0, out.length());
        osw.flush();
        osw.close();
        //response.getOutputStream().print(out);
        //throw new Exception(out);
        } catch (Exception e) {
            response.sendError(500, e.getMessage());
        } finally {
            response.getOutputStream().close();
        }

        return ;
    }




    @RequestMapping("/run")
    public ModelAndView run() {
        ModelAndView ret = new ModelAndView("run");
        return ret;
    }

    @RequestMapping("/new")
    public ModelAndView newPage() {
        ModelAndView ret = new ModelAndView("new");
        ret.addObject("posturl", blobstoreService.createUploadUrl("/save"));
        return ret;
    }

    @RequestMapping(value="/savew", method=RequestMethod.POST)
    public ModelAndView save(@RequestParam("title") String title, @RequestParam("content") String content,
            @RequestParam("imagefile") GMultipartFile imagefile) throws FileUploadException, IOException {
        //System.out.println(imagefile.getSize());
        pageStore.storePage(title, content, "");
        
        return new ModelAndView("run");
    }
    @RequestMapping(value="/save", method=RequestMethod.POST)
    public void upload(HttpServletRequest request, HttpServletResponse res) {
        Map<String, BlobKey> blobs = blobstoreService.getUploadedBlobs(request);
        BlobKey blobKey = blobs.get("imagefile");
        BlobInfoFactory bif = new BlobInfoFactory();
        BlobInfo blobInfo = bif.loadBlobInfo(blobKey);
        String title = request.getParameter("title");
        String content = request.getParameter("content");
        if (blobInfo.getSize() != 0) {
            pageStore.storePage(title, content, blobKey.getKeyString());
        } else {
             pageStore.storePage(title, content);
        }
    }
    @RequestMapping(value="/image/{key}", method=RequestMethod.GET)
    public void image(@PathVariable("key") String key, HttpServletResponse res) throws IOException {
        BlobKey blobKey = new BlobKey(key);
        blobstoreService.serve(blobKey, res);
    }

}
